package com.celeste.mcpserverfeishu.service.impl;

import com.celeste.mcpserverfeishu.api.FeishuApi;
import com.celeste.mcpserverfeishu.dto.FeishuResponse;
import com.celeste.mcpserverfeishu.dto.block.CreateBlockRequest;
import com.celeste.mcpserverfeishu.dto.block.CreateBlockResponse;
import com.celeste.mcpserverfeishu.dto.document.CreateDocumentRequest;
import com.celeste.mcpserverfeishu.dto.document.CreateDocumentResponse;
import com.celeste.mcpserverfeishu.dto.document.GetDocumentContentResponse;
import com.celeste.mcpserverfeishu.service.FeishuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * 飞书服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FeishuServiceImpl implements FeishuService {

    private final FeishuApi feishuApi;

    @Override
    public CreateDocumentResponse.Document createDocument(String accessToken, String title, String folderToken) {
        String authorization = formatAuthorization(accessToken);
        CreateDocumentRequest request = CreateDocumentRequest.builder()
                .title(title)
                .folder_token(folderToken)
                .build();

        try {
            Response<FeishuResponse<CreateDocumentResponse>> response = feishuApi
                    .createDocument(authorization, request)
                    .execute();

            if (response.isSuccessful() && response.body() != null) {
                FeishuResponse<CreateDocumentResponse> feishuResponse = response.body();
                if (feishuResponse.getCode() == 0 && feishuResponse.getData() != null) {
                    return feishuResponse.getData().getDocument();
                } else {
                    throw new RuntimeException("创建文档失败: " + feishuResponse.getMsg());
                }
            } else {
                throw new RuntimeException("创建文档API调用失败: " + response.errorBody().string());
            }
        } catch (Throwable e) {
            log.error("创建文档异常", e);
            throw new RuntimeException("创建文档异常", e);
        }
    }

    @Override
    public String getDocumentContent(String accessToken, String documentId) {
        String authorization = formatAuthorization(accessToken);

        try {
            Response<FeishuResponse<GetDocumentContentResponse>> response = feishuApi
                    .getDocumentContent(authorization, documentId)
                    .execute();

            if (response.isSuccessful() && response.body() != null) {
                FeishuResponse<GetDocumentContentResponse> feishuResponse = response.body();
                if (feishuResponse.getCode() == 0 && feishuResponse.getData() != null) {
                    return feishuResponse.getData().getContent();
                } else {
                    throw new RuntimeException("获取文档内容失败: " + feishuResponse.getMsg());
                }
            } else {
                throw new RuntimeException("获取文档内容API调用失败: " + response.errorBody().string());
            }
        } catch (Throwable e) {
            log.error("获取文档内容异常", e);
            throw new RuntimeException("获取文档内容异常", e);
        }
    }

    @Override
    public CreateBlockResponse.Block addTextToDocument(String accessToken, String documentId, String content) {
        String authorization = formatAuthorization(accessToken);
        
        // 创建文本块请求
        CreateBlockRequest.TextElementStyle textStyle = CreateBlockRequest.TextElementStyle.builder().build();
        CreateBlockRequest.TextRun textRun = CreateBlockRequest.TextRun.builder()
                .content(content)
                .text_element_style(textStyle)
                .build();
        CreateBlockRequest.TextElement textElement = CreateBlockRequest.TextElement.builder()
                .text_run(textRun)
                .build();
        CreateBlockRequest.Text text = CreateBlockRequest.Text.builder()
                .elements(Collections.singletonList(textElement))
                .style(Collections.emptyMap())
                .build();
        CreateBlockRequest.Block block = CreateBlockRequest.Block.builder()
                .block_type(2) // 文本块类型
                .text(text)
                .build();
        CreateBlockRequest request = CreateBlockRequest.builder()
                .index(0)
                .children(Collections.singletonList(block))
                .build();

        try {
            Response<FeishuResponse<CreateBlockResponse>> response = feishuApi
                    .createBlock(authorization, documentId, documentId, request)
                    .execute();

            if (response.isSuccessful() && response.body() != null) {
                FeishuResponse<CreateBlockResponse> feishuResponse = response.body();
                if (feishuResponse.getCode() == 0 && feishuResponse.getData() != null) {
                    List<CreateBlockResponse.Block> blocks = feishuResponse.getData().getChildren();
                    if (blocks != null && !blocks.isEmpty()) {
                        return blocks.get(0);
                    }
                    throw new RuntimeException("创建文本块失败: 返回数据为空");
                } else {
                    throw new RuntimeException("创建文本块失败: " + feishuResponse.getMsg());
                }
            } else {
                throw new RuntimeException("创建文本块API调用失败: " + response.errorBody().string());
            }
        } catch (Throwable e) {
            log.error("创建文本块异常", e);
            throw new RuntimeException("创建文本块异常", e);
        }
    }

    /**
     * 格式化授权信息
     *
     * @param accessToken 访问令牌
     * @return 格式化后的授权信息
     */
    private String formatAuthorization(String accessToken) {
        return "Bearer " + accessToken;
    }
} 